<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="width: 300px">
      <el-breadcrumb-item style="font-size: 16px">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px"
        >用户列表管理</el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="search">
      <el-input
        style="width: 200px"
        placeholder="请输入用户名"
        v-model="username"
        @blur="getUserList_Token()"
      ></el-input>
      <el-button @click="getUserList()" type="primary" icon="el-icon-search"
        >搜索</el-button
      >
    </div>
    <div class="addUser">
      <!-- 对话框组件  :visible.sync(设置是否显示对话框) width(设置对话框的宽度)
:before-close(在对话框关闭前触发的事件) -->
      <div class="addForm">
        <el-dialog
          title="添加用户"
          :visible.sync="addDialogVisible"
          width="40%"
          @close="addDialogClosed()"
          class="addDialog"
        >
          <!-- 对话框主体区域 -->
          <el-form
            :model="addForm"
            :rules="addFormRules"
            ref="addFormRef"
            label-width="80px"
            style="padding: 10px 20px"
          >
            <el-form-item label="用户名" prop="name" style="height: 50px">
              <el-input
                v-model="addForm.name"
                style="width: 50%"
                maxlength="16"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" style="height: 50px">
              <el-input v-model="addForm.email" style="width: 50%"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" style="height: 50px">
              <el-input
                v-model="addForm.password"
                style="width: 50%"
                maxlength="16"
              ></el-input>
            </el-form-item>
            <el-form-item label="高考科目" prop="type" style="height: 50px">
              <el-radio-group v-model="addForm.type">
                <el-radio label="理科"></el-radio>
                <el-radio label="文科"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="高考成绩" prop="score" style="height: 50px">
              <el-input
                v-model.number="addForm.score"
                style="width: 50%"
                maxlength="3"
              ></el-input>
            </el-form-item>
          </el-form>
          <!-- 对话框底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="addCancel">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
      </div>

      <el-button
        v-if="showAdd"
        type="primary"
        @click="showAddDialog()"
        style="float: right; margin-top: -41px; margin-right: 60px"
        >添加用户</el-button
      >
    </div>
    <el-table
      :data="userData"
      border
      style="width: 961px; margin-left: 40px; height: 390px"
      :header-cell-style="headClass"
    >
      <el-table-column label="序号" width="70" type="index" align="center">
      </el-table-column>
      <el-table-column label="用户名" width="150" prop="name" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="250" prop="email" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="高考科目" width="120" prop="type" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="高考成绩" width="150" prop="score" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="showEdit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.name)"
          ></el-button>

          <el-button
            v-if="showRemove && disableData[scope.$index] === 0"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeUserById(scope.row.name)"
          ></el-button>
          <el-button
            v-if="disableData[scope.$index] === 1"
            disabled
            size="mini"
            type="danger"
            icon="el-icon-delete"
          ></el-button>
          <el-button
            v-if="showBan && disableData[scope.$index] === 0"
            type="warning"
            size="mini"
            @click="banUser(scope.$index, scope.row.id)"
          >
            封禁
          </el-button>
          <el-button
            v-if="disableData[scope.$index] === 1"
            disabled
            type="warning"
            size="mini"
          >
            已封
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="editForm">
      <el-dialog
        title="修改信息"
        :visible.sync="editDialogVisible"
        width="400px"
        @close="editDialogClosed"
        class="editDialog"
        top="20px"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
          <el-form-item label="用户名" prop="name">
            <el-input
              v-model="editForm.name"
              autocomplete="off"
              maxlength="16"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="editForm.password"
              autocomplete="off"
              maxlength="16"
            ></el-input>
          </el-form-item>
          <el-form-item label="高考科目" prop="type">
            <el-radio-group v-model="editForm.type">
              <el-radio label="理科"></el-radio>
              <el-radio label="文科"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="高考成绩" prop="score">
            <el-input
              v-model.number="editForm.score"
              autocomplete="off"
              maxlength="3"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <el-pagination
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-size="queryInfo.pagesize"
      layout="total, prev, pager, next"
      :total="queryInfo.count"
      background
    >
      <!--
        @current-change(页码发生改变时触发)
        :current-page(设置当前页码)
        :page-size(设置每页的数据条数)
        :total(设置总页数)
     -->
    </el-pagination>
  </el-card>
</template>

<script>
import qs from "qs";
import Base64 from "base-64";
import throttling from "@/public/throttling.js";
export default {
  data() {
    var validateName = (rule, value, callback) => {
      let reg = /^[^_]\S{2,16}[^_]$/;
      if (!value) {
        callback(new Error("用户名不可为空!"));
      } else {
        if (!reg.test(value)) {
          callback(
            new Error("用户名不能以下划线开头和结尾，且必须大于2位！！")
          );
        } else {
          callback();
        }
      }
    };
    var validatePass = (rule, value, callback) => {
      let reg = /^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S{6,16}$/;
      if (!value) {
        callback(new Error("用户名不可为空!"));
      } else {
        if (value.length < 6) {
          callback(new Error("密码需大于6位!"));
        }
        if (value.length > 16) {
          callback(new Error("用户名需小于16位!"));
        } else if (!reg.test(value)) {
          callback(
            new Error(
              "密码需包含小写字母、大写字母、数字、特殊符号的两种及以上!"
            )
          );
        } else {
          callback();
        }
      }
    };
    //验证邮箱的规则
    var validataEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (!value) {
        callback(new Error("邮箱不可为空!"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("邮箱输入格式有误!请重新输入！"));
        } else {
          callback();
        }
      }
    };
    var validateScore = (rule, value, callback) => {
      // let reg = /^\d+\.\d+$/;
      if (!value) {
        callback(new Error("请填写高考成绩！"));
      } else {
        if (value < 100 || value > 750) {
          callback(new Error("请填写100~750之间整数！"));
        }
        if (!Number.isInteger(value)) {
          callback(new Error("请正确填写高考成绩！该值为数字！"));
        } else {
          callback();
        }
      }
    };
    return {
      // 搜索用户名
      username: "",
      // 按钮 显示隐藏
      showAdd: true,
      showEdit: true,
      showRemove: true,
      showBan: true,
      // 按钮是否禁用
      banDisable: false,
      // 控制修改院校
      editDialogVisible: false,
      // 添加用户
      addDialogVisible: false,
      addForm: {
        name: "",
        email: "",
        password: "",
        type: "",
        score: "",
      },
      addFormRules: {
        name: [{ required: true, validator: validateName, trigger: "blur" }],
        email: [{ required: true, validator: validataEmail, trigger: "blur" }],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        type: [
          {
            required: true,
            message: "请选择一个科目",
            trigger: "change",
          },
        ],
        score: [{ required: true, validator: validateScore, trigger: "blur" }],
      },
      // 修改用户的表单数据
      editForm: {
        fname: "",
        name: "",
        email: "",
        password: "",
        type: "",
        score: "",
      },
      // 属性
      editFormRules: {
        name: [{ required: true, validator: validateName, trigger: "blur" }],
        email: [{ required: true, validator: validataEmail, trigger: "blur" }],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        type: [
          {
            required: true,
            message: "请选择一个科目",
            trigger: "change",
          },
        ],
        score: [{ required: true, validator: validateScore, trigger: "blur" }],
      },
      //初始分页条件
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 9,
        count: 0,
      },
      // 保存请求回来的用户列表数据
      userData: [
        {
          // order: 1,
          name: "wyf",
          email: "1959198478@qq.com",
          type: "理科",
          score: 750,
          disable: 0,
        },
      ],
      // 是否封禁
      disableData: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    // 表格表头
    headClass() {
      //表头居中显示
      return "color:rgba(255,101,0);font-weight:bold;font-size:16px";
    },

    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleCurrentChange: throttling(function (page) {
      this.queryInfo.pagenum = page;
      console.log("跳转了");
      // 重新按照pagenum发送请求 请求最新的数据
      this.getUserList_Token();
    }, 1000),
    getUserList_Token() {
      const token = window.sessionStorage.getItem("tokenvalue");
      this.$axios.defaults.headers.common["satoken"] = token;
      this.$axios
        .get("/back/users", {
          params: {
            page: this.queryInfo.pagenum,
            size: this.queryInfo.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.status === 666) {
            this.$message.error("请先登录");
            this.$router.replace("/login");
          } else if (res) {
            this.$message.success("获取用户列表成功！");
            this.userData = res.data.data;
            console.log(this.userData);
            this.queryInfo.count = res.data.code;
          }
        });
    },
    // 添加
    addDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.addFormRef.resetFields();
    },
    addCancel() {
      this.addDialogVisible = false;
      this.$message("取消修改");
    },
    showAddDialog() {
      //显示弹出窗
      this.addDialogVisible = true;
    },
    addUser: throttling(function () {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        else {
          this.$axios
            .post(
              "/back/user",
              qs.stringify({
                name: this.addForm.name,
                email: this.addForm.email,
                password: Base64.encode(this.addForm.password),
                type: this.addForm.type,
                score: this.addForm.score,
              })
            )
            .then((res) => {
              console.log(res);
              this.$message.success("添加用户成功！");
              this.disableData = [];
              //重新请求最新的数据
              this.$axios
                .get("/back/users", {
                  params: {
                    page: this.queryInfo.pagenum,
                    size: this.queryInfo.pagesize,
                  },
                })
                .then((res) => {
                  console.log(res);
                  if (res.data.status === 666) {
                    this.$message.error("请先登录");
                    this.$router.replace("/login");
                  } else if (res) {
                    this.userData = res.data.data;
                    this.userData.forEach((value) => {
                      this.disableData.push(value.disable);
                    });
                    console.log(this.userData);
                    console.log(this.disableData);
                    this.queryInfo.count = res.data.code;
                  }
                });
              this.addDialogVisible = false;
            });
        }
      });
    }, 1000),
    // 修改
    showEditDialog(name) {
      //将获取到的数据保存到数据editForm中
      this.editForm.fname = name;
      //显示弹出窗
      this.editDialogVisible = true;
    },
    editDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.editFormRef.resetFields();
    },

    cancel() {
      this.editDialogVisible = false;
      this.$message("取消修改");
    },
    editUser: throttling(function () {
      // // 用户点击修改表单中的确定按钮之后，验证表单数据
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        // 发送请求 完成修改用户的操作
        this.$axios
          .put(
            "/back/user",
            qs.stringify({
              fName: this.editForm.fname,
              name: this.editForm.name,
              email: this.editForm.email,
              password: Base64.encode(this.editForm.password),
              type: this.editForm.type,
              score: this.editForm.score,
            })
          )
          .then((res) => {
            console.log(res);
            //判断如果修改失败，就做提示
            if (res.data.code !== 200)
              return this.$message.error("修改用户失败");
            //修改成功的提示
            this.$message.success("修改用户成功");
            //关闭对话框
            this.editDialogVisible = false;
            //重新请求最新的数据
            this.getUserList_Token();
          });
      });
    }, 1000),
    removeUserById(name) {
      this.$axios.get("/back/user/deleteButton").then((res) => {
        console.log(res);
        if (res.data.code == 500) {
          this.$message.error("不好意思，你没有操作权限");
        } else {
          //弹出确定取消框，是否删除用户
          this.$confirm("请问是否要永久删除该用户", "删除提示", {
            distinguishCancelAndClose: true,
            confirmButtonText: "确认删除",
            cancelButtonText: "取消",
          })
            .then(() => {
              const token = window.sessionStorage.getItem("tokenvalue");
              this.$axios.defaults.headers.common["satoken"] = token;
              //发送请求根据id完成删除操作
              this.$axios.delete("/back/user/" + name).then((res) => {
                console.log(res);
                //判断如果删除失败，就做提示
                if (res.data.code === 500)
                  return this.$message.error(res.data.msg);
                else {
                  //修改成功的提示
                  this.$message.success("删除用户成功");
                  //重新请求最新的数据
                  this.getUserList_Token();
                }
              });
            })
            .catch((action) => {
              this.$message({
                type: "info",
                message: action === "cancel" ? "取消删除" : "放弃删除",
              });
            });
        }
      });
    },
    banUser: throttling(function (index, id) {
      //弹出确定取消框，是否删除用户
      this.$confirm("请问是否要永久封禁该用户", "删除提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认封禁",
        cancelButtonText: "取消",
      })
        .then(() => {
          const token = window.sessionStorage.getItem("tokenvalue");
          this.$axios.defaults.headers.common["satoken"] = token;
          //发送请求根据id完成删除操作
          this.$axios
            .put(
              "/back/user/disability",
              qs.stringify({
                id: id,
              })
            )
            .then((res) => {
              console.log(res);
              this.disableData = [];
              //重新请求最新的数据
              this.$axios
                .get("/back/users", {
                  params: {
                    page: this.queryInfo.pagenum,
                    size: this.queryInfo.pagesize,
                  },
                })
                .then((res) => {
                  console.log(res);
                  if (res.data.status === 666) {
                    this.$message.error("请先登录");
                    this.$router.replace("/login");
                  } else if (res) {
                    this.userData = res.data.data;
                    this.userData.forEach((value) => {
                      this.disableData.push(value.disable);
                    });
                    console.log(this.userData);
                    console.log(this.disableData);
                    this.queryInfo.count = res.data.code;
                  }
                });
            });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "取消封禁" : "放弃封禁",
          });
        });
    }, 1000),
  },
  created() {
    const token = window.sessionStorage.getItem("tokenvalue");
    this.$axios.defaults.headers.common["satoken"] = token;
    this.$axios.get("/back/user/updateButton").then((res) => {
      if (res.data.code === 500) {
        this.showAdd = false;
      }
    });
    this.$axios.get("/back/user/updateButton").then((res) => {
      if (res.data.code === 500) {
        this.showEdit = false;
      }
    });
    this.$axios.get("/back/user/deleteButton").then((res) => {
      if (res.data.code === 500) {
        this.showRemove = false;
      }
    });
    this.$axios.get("/back/user/disableButton").then((res) => {
      if (res.data.code === 500) {
        this.showBan = false;
      }
    });

    this.$axios
      .get("/back/users", {
        params: {
          page: this.queryInfo.pagenum,
          size: this.queryInfo.pagesize,
        },
      })
      .then((res) => {
        console.log(res);
        if (res.data.status === 666) {
          this.$message.error("请先登录");
          this.$router.replace("/login");
        } else if (res) {
          this.$message.success("获取用户列表成功！");
          this.userData = res.data.data;
          this.userData.forEach((value) => {
            this.disableData.push(value.disable);
          });
          console.log(this.disableData);
          this.queryInfo.count = res.data.code;
        }
      });
  },
};
</script>

<style scoped>
.box-card {
  margin: 22px auto 0px;
  min-height: 550px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.search {
  margin-top: 20px;
  margin-left: 40px;
  width: 400px;
}

.el-table {
  margin-top: 20px;
}

.editForm /deep/ .el-dialog {
  margin-top: 0;
}

.addDialog /deep/ .el-dialog__body {
  padding: 10px 20px;
}

.editDialog /deep/ .el-dialog__body {
  padding: 0 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.pagination {
  bottom: 0;
  width: 412px;
  margin: 5px auto;
}
</style>